package com.neo.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.neo.entity.errorMessage.RespErrorCode;
import com.neo.util.ErrorFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.neo.util.DjsStringUtil;

/**
 * 数据迁移—批量发送红包 
 * @author gaojun
 * @date 2017年12月31日
 *
 */
@Service
public class DjsBatchRedEnvelopService {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	//获取当前日期
	Date nowDate = new Date();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	String strDate = sdf.format(nowDate);
	
	public String generalFile(String batch) throws Exception{
		String sql = "SELECT ua.USERNAME,ub.ACCOUNT_ID as ACCOUNT_ID,(ua.CURR_BAL-IFNULL(ip.AMT_PAID,0)) as CURR_BAL,ub.FULL_NAME as FULL_NAME "
				+ "FROM inv_user_account ua "
				+ "INNER JOIN jx_user_bankcard ub ON ua.USERNAME = ub.USERNAME "
				+ "LEFT JOIN (SELECT USERNAME,SUM(AMT_PAID) AS AMT_PAID FROM inv_red_pay_record GROUP BY USERNAME)ip ON ua.USERNAME = ip.USERNAME "
				+ "WHERE ub.STATUS = 1";
		List<Map<String,Object>> list = 
				jdbcTemplate.queryForList(sql,new Object[]{});
		
		List<String> resList = new ArrayList<>();
		for(Map<String,Object> map : list){
			String accountId = (String)map.get("ACCOUNT_ID");//电子账户
			String fullName = (String)map.get("FULL_NAME");//开户姓名
			BigDecimal voucherAmt = (BigDecimal)map.get("CURR_BAL");//余额
			
			if(voucherAmt.compareTo(BigDecimal.ZERO) <= 0){
				continue;
			}
			
			voucherAmt = voucherAmt.setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_DOWN);//去2位小数再变整数
			String res = DjsStringUtil.BANKID
				+batch
				+DjsStringUtil.fillBlank(strDate,8)//日期
				+DjsStringUtil.fillBlank("001", 3)//业务类别 001-红包发放 002-加息券收益发放
				+DjsStringUtil.fillBlank(accountId, 19)//转入方电子账户
				+DjsStringUtil.fillLeftZero(voucherAmt.toString(), 12)//入账金额
				+DjsStringUtil.fillBlank("156", 3)//币种 156：人民币
				+DjsStringUtil.fillBlank(fullName, 60)//持卡人姓名
				+DjsStringUtil.fillBlank("", 40)//自定义描述
				+DjsStringUtil.fillBlank("", 100)//保留域
				+DjsStringUtil.fillBlank("", 100);//第三方保留
			
			//System.out.println(res);
			
			byte[] bs = res.getBytes("GBK");
			if (bs.length!=355) {
				System.out.println("长度错误");
			};
			resList.add(res);		
		}
		System.out.println("生成文件行数"+resList.size());

		//文件名
		String fileName = DjsStringUtil.FILE_PATH+DjsStringUtil.BANKID+"-TRQT-"+DjsStringUtil.COINSTCODE+"-"+batch+"-"+strDate;
		//写出文件
		DjsStringUtil.writeStringToFile(resList, batch, fileName);
		
		return fileName;
	}
	
	/**
	 * 读取批量发红包即信返回文件
	 * @author gaojun
	 * @date 2017年12月3日
	 * 
	 * @param list
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> readResFile(List<String> list) throws Exception{
		
		int res_f = 0;
		int res_s = 0;
		Map<String, String> result = new HashMap<>();
		List<String> errData = new ArrayList<>();
		for(String str : list){
			String accountId = DjsStringUtil.cutByGBK(str, 21, 19);
			String result1 = DjsStringUtil.cutByGBK(str, 53, 2);
			String amount = DjsStringUtil.cutByGBK(str, 41, 12);
			boolean isSuccess = false;
			if("00".equals(result1)){
				isSuccess = false;
			}
			
			if(isSuccess){
				System.out.println("电子账户:" + accountId + "," + codeToMsg(result1));
				String selectSql = "SELECT USERNAME FROM jx_account_info WHERE USERNAME = '" + accountId + "'";
				List<Map<String,Object>> maps = jdbcTemplate.queryForList(selectSql,new Object[]{});
				String username = "";
				if(maps != null && maps.size() > 0){
					username = (String)maps.get(0).get("USERNAME");
				}
				StringBuilder insertSql = new StringBuilder("INSERT INTO inv_red_pay_record(USERNAME,AMT_PAID,CREATE_TIME) VALUES(");
				insertSql.append("'" + username + "',");
				insertSql.append("'" + amount + "',");
				insertSql.append("'" + new Date().toString() + "'");
				insertSql.append(")");
				int resultNums = jdbcTemplate.update(insertSql.toString());
				if(resultNums < 1){
					throw new Exception("电子账户:" + accountId + ",插入数据时异常..");
				}
				res_s++;
			}else{
				String[] arry1 = {"10","11","12","13","14","15","16","17","18"};
				String[] arry2 = {"21","22","23","24","25","26","27","28"};
				List<String> arrayList1 = Arrays.asList(arry1);
				List<String> arrayList2 = Arrays.asList(arry2);
				if (arrayList1.contains(result1)){
					result1 = "10";
				}
				if (arrayList2.contains(result1)){
					result1 = "21";
				}
				if ("其他".equals(result1)){
					result1 = "94";
				}
				System.out.println("电子账户:" + accountId + ",交易失败," + codeToMsg(result1));
				errData.add(new StringBuffer("失败原因：").append(RespErrorCode.getName("TRQTRES" + result1)).append("，原数据为=========>").append(str).toString());
				res_f++;
			}
		}
		if (errData.size() > 0) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			result = ErrorFileUtil.handle(errData, "APPZXErrorDataFile" + simpleDateFormat.format(new Date()) + "00" + res_f + res_s);
		}
		result.put("失败F条数", res_f + "");
		result.put("成功S条数", res_s + "");
		result.put("处理总数", list.size() + "");
		return result;
	}
	
	private String codeToMsg(String errorCode){
		if("00".equals(errorCode)){
			return "交易成功";
		}
		if("10".equals(errorCode) || "11".equals(errorCode)
				|| "12".equals(errorCode) || "13".equals(errorCode)
				|| "14".equals(errorCode) || "15".equals(errorCode)
				|| "16".equals(errorCode) || "17".equals(errorCode) || "18".equals(errorCode)){
			return "错误代号:" + errorCode + ",平台电子帐号异常";
		}
		if("21".equals(errorCode) || "22".equals(errorCode) || "23".equals(errorCode)
				|| "24".equals(errorCode) || "25".equals(errorCode) || "26".equals(errorCode)
				|| "27".equals(errorCode) || "28".equals(errorCode)){
			return "错误代号:" + errorCode + ",转入方电子帐号异常";
		}
		if("20".equals(errorCode)){
			return "错误代号:" + errorCode + ",转入方电子帐号交易权限校验失败";
		}
		if("35".equals(errorCode)){
			return "错误代号:" + errorCode + ",转出方余额不足";
		}
		if("36".equals(errorCode)){
			return "错误代号:" + errorCode + ",转入方余额不足";
		}
		if("70".equals(errorCode)){
			return "错误代号:" + errorCode + ",文件内银行号与文件名不一致";
		}
		if("72".equals(errorCode)){
			return "错误代号:" + errorCode + ",文件内批次号与文件名不一致";
		}
		if("73".equals(errorCode)){
			return "错误代号:" + errorCode + ",币种不能为空";
		}
		if("74".equals(errorCode)){
			return "错误代号:" + errorCode + ",金额不能为空";
		}
		if("81".equals(errorCode)){
			return "错误代号:" + errorCode + ",姓名校验失败";
		}
		if("85".equals(errorCode)){
			return "错误代号:" + errorCode + ",平台账户不存在";
		}
		if("93".equals(errorCode)){
			return "错误代号:" + errorCode + ",姓名不能为空";
		}
		return "错误代号:" + errorCode + ",其他错误";
	}
}
